package org.nf.trading.service.app.user.impl;


import com.github.pagehelper.PageInfo;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.nf.trading.dao.UserMapper;
import org.nf.trading.dto.*;
import org.nf.trading.entity.User;
import org.nf.trading.exception.app.user.LoginException;
import org.nf.trading.service.app.user.UserService;
import org.nf.trading.util.JwtUtils;
import org.nf.trading.util.Md5Util;
import org.nf.trading.vo.ResultVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

@Service
@RequiredArgsConstructor
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;

//    private final NotifyWebSocketServerHandler notifyWebSocketServerHandler;

    /**
     * 手机号和密码登录
     *
     * @param phone
     * @param pwd
     * @return
     */
    @Override
    public UserDTO loginAuthPwd(String phone, String pwd, HttpServletRequest request) {
        User user = userMapper.getUserByPhone(phone);
        if (user == null) {
            throw new LoginException(500, "用户不存在");
        }
        if (!Md5Util.equals(pwd, user.getUserPwd()) && phone.equals(user.getUserPhone())) {
            throw new LoginException(500, "账号密码错误！");
        }
        //放到会话当中
//        request.getSession().setAttribute("userId",user.getUserId());
//        notifyWebSocketServerHandler.setUserId(user.getUserId().toString());

        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", user.getUserId());
        String token = JwtUtils.createToken(map, 1000 * 60 * 60 * 24);
        return new UserDTO(token, user.getUserId());
    }

    /**
     * 生成验证码
     *
     * @param phone
     * @return
     */
    @Override
    public void generateCode(String phone) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("https://api.recruit.lldwb.top/api/login/sendAuthCode?userPhone=" + phone)
                .method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Accept", "*/*")
                .addHeader("Host", "api.recruit.lldwb.top")
                .addHeader("Connection", "keep-alive")
                .build();
        try {
            Response response = client.newCall(request).execute();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 登录验证码登录
     *
     * @param phone
     * @param
     * @return
     */
    @Override
    public UserDTO loginAuth(String phone, String code) {
        if (phone == null) {
            throw new LoginException(500, "手机号为空");
        }
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("userPhone", phone);
        paramMap.put("authCode", code);

        String result = HttpUtil.post("https://api.recruit.lldwb.top/api/login/login", paramMap);
        log.info(result);
//        Map<String,String> mapData = null;
        LoginAuthDTO loginAuthDTO = null;
        try {
            loginAuthDTO = new ObjectMapper().readValue(result, LoginAuthDTO.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        log.info("值：{}",loginAuthDTO);
        log.info("code： {}",loginAuthDTO.getCode());
        if (loginAuthDTO.getCode() == 200){
            User user = userMapper.getUserByPhone(phone);
            //判断是否存在此用户，不存在则创建新用户
            if (user == null) {
                User user1 = new User();
                user1.setUserPhone(phone);
                user1.setUserName(generateRandomUsername(10));
                userMapper.insert(user1);

                HashMap<String, Object> map = new HashMap<>();
                map.put("uid", user1.getUserId());
                String token = JwtUtils.createToken(map, 1000 * 60 * 60 * 24);
                return new UserDTO(token, user1.getUserId());
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("uid", user.getUserId());
            String token = JwtUtils.createToken(map, 1000 * 60 * 60 * 24);
            return new UserDTO(token, user.getUserId());
        } else {
            throw new LoginException(500, "验证码登录失败");
        }
    }

    private static String generateRandomUsername(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        return sb.toString();
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @Override
    public String register(User user) {
        //判断是否为空
        if ("".equals(user.getUserPhone()) || "".equals(user.getUserPwd())) {
            throw new LoginException(500, "用户参数不能为空");
        }
        user.setUserPwd(Md5Util.encode(user.getUserPwd()));
        int insert = userMapper.insert(user);
        if (insert == 0) {
            throw new LoginException(500, "注册失败,服务器内部异常！");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", user.getUserId());
        String token = JwtUtils.createToken(map, 120000);
        return token;
    }

    /**
     * 通过id查询一个用户
     *
     * @param uId
     * @return
     */
    @Override
    public User selectByPrimaryKey(Integer uId) {
        if (uId == null || uId == 0) {
            throw new LoginException(500, "用户id不能为空");
        }
        User user = userMapper.selectByPrimaryKey(uId);
        return user;
    }

    @Override
    public PageInfo<User> selectUserAll(Integer pageNum, Integer pageSize, String userName,String phone) {
        return new PageInfo<>(userMapper.selectAll(pageNum, pageSize, userName,phone));
    }

    /**
     * 查询发送人和接收人
     * @param users
     * @return
     */
    @Override
    public List<CommentMessageDTO> listUser(MessageDTO[] users) {
        List<CommentMessageDTO> commentMessageDTOS = new ArrayList<>();
        for (MessageDTO user : users) {
            CommentMessageDTO commentMessageDTO = new CommentMessageDTO();
            User senderUser = userMapper.getUserId(user.getSenderId());
            User receiverUser = userMapper.getUserId(user.getReceiveId());
            commentMessageDTO.setSenderUser(senderUser);
            commentMessageDTO.setReceiverUser(receiverUser);
            commentMessageDTO.setContent(user.getContent());
            commentMessageDTOS.add(commentMessageDTO);
        }
        Collections.sort(commentMessageDTOS, new Comparator<CommentMessageDTO>() {
            @Override
            public int compare(CommentMessageDTO o1, CommentMessageDTO o2) {
                return -1;
            }
        });
        log.info("评论消息为：{}",commentMessageDTOS);
        return commentMessageDTOS;
    }
}
